package com.well.menjin.dao.impl;

import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.util.StringUtils;

import com.well.menjin.dao.IRoomDao;
import com.well.menjin.domain.Room;
import com.well.menjin.model.Sort;
import com.well.menjin.service.IRoomService;

@Repository
public class RoomDaoImpl implements IRoomDao{

	@Autowired
	private SessionFactory sessionFactory;
	
	@SuppressWarnings("unchecked")
	@Override
	public List<Room> getRooms(int start, int limit, int page, List<Sort> sorts2, String controllerid, String roomname,
			String ipaddress) {
		Criteria criteria = sessionFactory.getCurrentSession().createCriteria(Room.class).
				setFirstResult(start).setMaxResults(limit);
		if (!StringUtils.isEmpty(controllerid)) {
			criteria.add(Restrictions.like("controller_id", "%"+controllerid+"%"));
		}
		if (!StringUtils.isEmpty(roomname)) {
			criteria.add(Restrictions.like("room_name", "%"+roomname+"%"));
		}
		if (!StringUtils.isEmpty(ipaddress)) {
			criteria.add(Restrictions.like("ip_address", "%"+ipaddress+"%"));
		}
		if (sorts2!=null&&sorts2.size()>0) {
			for(Sort sort:sorts2){
				if ("asc".equalsIgnoreCase(sort.getDirection())) {
					criteria.addOrder(Order.asc(sort.getProperty()));
				}else {
					criteria.addOrder(Order.desc(sort.getProperty()));
				}
			}
		}
		return criteria.list();
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<Room> getRoomsCount(String controllerid, String roomname, String ipaddress) {
		Criteria criteria = sessionFactory.getCurrentSession().createCriteria(Room.class);
		if (!StringUtils.isEmpty(controllerid)) {
			criteria.add(Restrictions.like("controller_id", "%"+controllerid+"%"));
		}
		if (!StringUtils.isEmpty(roomname)) {
			criteria.add(Restrictions.like("room_name", "%"+roomname+"%"));
		}
		if (!StringUtils.isEmpty(ipaddress)) {
			criteria.add(Restrictions.like("ip_address", "%"+ipaddress+"%"));
		}
		return criteria.list();
	}

}
